package com.gopay.bis.njcb.ebank.impl;

import com.gopay.bis.njcb.ebank.operation.NjcbB2cCertHelper;
import com.gopay.bis.njcb.ebank.operation.NjcbB2cQueryHelper;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.njcb.ebank.NjcbB2cMessage;
import com.gopay.common.domain.bank.njcb.ebank.query.request.NjcbeBankDataReq;
import com.gopay.common.domain.bank.njcb.ebank.query.response.NjcbeBankDataRep;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.businesses.BankService;

public class NjcbB2cBankServiceImpl implements BankService {

	private NjcbB2cCertHelper njcbB2cCertHelper;

	private NjcbB2cQueryHelper njcbB2cQueryHelper;

	public Object query(Object arg) throws GopayException {
		NjcbeBankDataReq reqMessage = (NjcbeBankDataReq) arg;
		String signStr = njcbB2cQueryHelper.buildQuerySignStr(reqMessage);
		NjcbB2cMessage b2cMessage = new NjcbB2cMessage();
		b2cMessage.setOutStlmCd(BankConstants.BANK_LOGO_NJCB);
		b2cMessage.setPlainMessage(signStr);
		b2cMessage.setPrivateKeyPath(reqMessage.getPrivateKeyPath());
		b2cMessage.setPrivatePwd(reqMessage.getPrivatePwd());
		reqMessage.setPlainMessage(signStr);
		String signData = njcbB2cCertHelper.sign(b2cMessage);
		reqMessage.setSignMessage(signData);
		String[] certSign = signData.split("\\|\\|");
		b2cMessage.setSignMessage(certSign[0]);
		String queryResult = (String) njcbB2cQueryHelper.Query(reqMessage);
		NjcbeBankDataRep message = njcbB2cQueryHelper.parseMessage(queryResult);
		NjcbB2cMessage verifyMessage = new NjcbB2cMessage();
		verifyMessage.setPlainMessage(message.getPlainMessage());
		verifyMessage.setSignMessage(message.getSignData());
		verifyMessage.setOutStlmCd(BankConstants.BANK_LOGO_NJCB);
		verifyMessage.setPublicKeyPath(reqMessage.getPublicKeyPath());
		Boolean isVerify = (Boolean)njcbB2cCertHelper.verify(verifyMessage);
		if(isVerify){
			return message;
		}else{
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
		}

	}

	public Object sign(BaseMessage message) throws GopayException {
		NjcbB2cMessage njcbB2cMessage = (NjcbB2cMessage) message;
		return njcbB2cCertHelper.sign(njcbB2cMessage);
	}

	public Object verify(BaseMessage message) throws GopayException {
		NjcbB2cMessage njcbB2cMessage = (NjcbB2cMessage) message;
		return njcbB2cCertHelper.verify(njcbB2cMessage);
	}

	public void setNjcbB2cCertHelper(NjcbB2cCertHelper njcbB2cCertHelper) {
		this.njcbB2cCertHelper = njcbB2cCertHelper;
	}

	public void setNjcbB2cQueryHelper(NjcbB2cQueryHelper njcbB2cQueryHelper) {
		this.njcbB2cQueryHelper = njcbB2cQueryHelper;
	}

	@Override
	public Object dayend(Object obj) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(Object obj) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

}
